package com.cloud.common.validator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ValidatorHelper {
    private static final String SEPERATOR = ",";

    @Autowired
    private Validator validator;

    /**
     * 验证bean属性
     *
     * @param bean
     * @return String
     */
    public String validate(Object bean) {
        Set<ConstraintViolation<Object>> failures = validator.validate(bean);
        if (!failures.isEmpty()) {
            List<String> msgList = failures.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
            return StringUtils.join(msgList, SEPERATOR);
        }
        return null;
    }

}
